package com.zmn.brs.admin.controller.record;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.brs.common.enums.WronLevelEnum;
import com.zmn.brs.drools.bean.ObjectiveMonitor;
import com.zmn.brs.drools.bean.ObjectiveMonitorData;
import com.zmn.brs.model.entity.record.EventRecordQuery;
import com.zmn.brs.model.query.record.ObjectiveRecordCustom;
import com.zmn.brs.model.query.record.ObjectiveRecordCustomQuery;
import com.zmn.brs.model.vo.record.EventRecordVO;
import com.zmn.brs.services.interfaces.record.EventRecordService;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述： 绩效监控数据
 * @author chongw
 * @since 2021-06-10 11:42
 */
@Slf4j
@RestController
@RequestMapping("/brs/record/objective/")
public class ObjectiveRecordListController {

    @Resource
    private EventRecordService eventRecordService;

    /**
     * 绩效监控数据列表
     * @author chongw
     * @since 2021-06-10 17:55:07
     */
    @RequestMapping("/list")
    @RequiresPermissions("/brs/record/objective/list.action")
    public ModelAndView list(@ModelAttribute ObjectiveRecordCustomQuery query) {
        query.setExportLimit(StaffAdminService.currentStaff().getExportLimit());
        Optional<ObjectiveRecordCustomQuery> optional = Optional.ofNullable(query).map(o -> {
            o.setPageSize(Optional.ofNullable(o.getPageSize()).orElse(20));
            o.setPagesNumber(Optional.ofNullable(o.getPagesNumber()).orElse(1));
            return o;
        });
        //查询绩效监控数据
        List<ObjectiveRecordCustom> list = this.getRecordVoList(query);
        ModelAndView mav = new ModelAndView("objective/record/list");
        mav.addObject("vo" , optional.get());
        mav.addObject("items" , list);
        boolean showExportExcel = StaffAdminService.isPermitted("/brs/record/objective/list.action");
        mav.addObject("showExportExcel", showExportExcel);
        mav.addObject("dayLimit", 0 - Optional.ofNullable(StaffAdminService.currentStaff().getDayLimit()).orElse(0));
        return mav;
    }

    /**
     * 绩效监控数据
     * @param query
     * @return
     */
    protected List<ObjectiveRecordCustom> getRecordVoList(ObjectiveRecordCustomQuery query){
        //设置监控周期
        if (StringUtil.isNotBlank(query.getTimeSearch())) {
            String[] timeRangeArray = query.getTimeSearch().split("-");
            query.setStartSearchTime(timeRangeArray[0].trim() + " 00:00:00");
            query.setEndSearchTime(timeRangeArray[1].trim() + " 23:59:59");
        }
        Integer dayLimit = StaffAdminService.currentStaff().getDayLimit();
        if (dayLimit != null && dayLimit == 0) {
            return new ArrayList<>();
        }
        if (dayLimit != null) {
            Date date = DateUtil.addDays(new Date(), -dayLimit);
            String startTime = query.getStartSearchTime();
            if (startTime == null) {
                query.setStartSearchTime(DateUtil.dateFormatToString(date, DateUtil.FORMAT_DEFAULT));
            } else {
                if (DateUtil.dateFormatToDate(startTime, DateUtil.FORMAT_DATE3 + " HH:mm:ss").before(date)) {
                    query.setStartSearchTime(DateUtil.dateFormatToString(date, DateUtil.FORMAT_DEFAULT));
                }
            }
            if (query.getEndSearchTime() == null) {
                query.setEndSearchTime(DateUtil.dateFormatToString(new Date(), DateUtil.FORMAT_DEFAULT));
            }
        }
        //查询绩效监控数据
        List<ObjectiveRecordCustom> items = Optional.ofNullable(eventRecordService.listObjectiveRecordPageByQuery(query)).orElse(new ArrayList<ObjectiveRecordCustom>());
        List<ObjectiveRecordCustom> list =  items.stream().map(o -> {
            if(StringUtil.isNotBlank(o.getExpand())){
                ObjectiveMonitorData data = JSONObject.parseObject(o.getExpand(), ObjectiveMonitorData.class);
                o.setLevel(data.getLevel());
                o.setExecutionDesc(String.format("实际目标%s-预期目标%s-完成率%s",
                        data.getCubeRealValue(), data.getCubeObjectiveValue(), data.getCubeObjectiveRatioValue().replace("%","")+"%"));
            }
            o.setMonitorCycleTime(String.format("%s ~ %s",
                    DateUtil.dateFormatToString(o.getCreateTime(),DateUtil.FORMAT_DATE_01),
                    DateUtil.dateFormatToString(o.getCreateTime(),DateUtil.FORMAT_DATE)));
            return o;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 描述: 导出监控记录
     * @param query 查询条件
     * @author chongw
     * @since 2021/06/21
     **/
    @RequestMapping(value = "/exportRecordExcel")
    public void exportRecordExcel(HttpServletResponse response, ObjectiveRecordCustomQuery query) {
        query.setPageIndex(1);
        query.setPageSize(StaffAdminService.currentStaff().getExportLimit());
        List<ObjectiveRecordCustom> recordVOList = getRecordVoList(query);
        List<List> lists = Lists.newArrayListWithExpectedSize(recordVOList.size());
        String[] title = {"部门", "责任人", "事件", "监控周期", "预警等级", "完成情况", "日期"};
        lists.add(Arrays.asList(title));
        recordVOList.forEach(e -> {
            List<Object> item = new ArrayList<>();
            item.add(e.getData().getDeptName());
            item.add(e.getData().getObjMasterName());
            item.add(e.getEventName());
            item.add(e.getMonitorCycleTime());
            item.add(WronLevelEnum.getLevelName(e.getLevel()));
            item.add(e.getExecutionDesc());
            item.add(DateUtil.toString(e.getCreateTime()));
            lists.add(item);
        });
        try {
            String excelName =  "绩效监控数据.xlsx";
            String name = new String(excelName.getBytes(), StandardCharsets.ISO_8859_1);
            ExcelUtil.export(response, lists, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出报表出错" + e.getMessage(), e);
        }

    }

}
